package com.cloud.customtoastdemo.toast

import android.content.Context
import android.graphics.PixelFormat
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import com.cloud.customtoastdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @auth: njb
 * @date: 2024/10/13 16:56
 * @desc: 描述
 */
object EasyToast {
    private lateinit var easyToastView: View
    private var mWindowManager: WindowManager? = null
    private var mToastJob: Job? = null
    private val TAG = "EasyToast"

    /**
     *
     * @param context window上下文
     * @param message 自定义的提示内容消息
     * @param duration 可动态设置在的显示时间
     * @param gravity 窗口显示位置 top、center、bottom
     */
    fun showCustomToast(context: Context, message: String, duration: Int, gravity: Int) {
        mWindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

        easyToastView = inflater.inflate(R.layout.custom_easy_toast, null)
        easyToastView?.let {
            val textView = it.findViewById<TextView>(R.id.tv_message)
            textView?.text = message
        }
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT
        )
        params.gravity = gravity
        params.x = 0
        params.y = 0

        if (easyToastView?.parent == null) {
            mWindowManager?.addView(easyToastView, params)
        }
        mToastJob?.cancel()
        mToastJob = CoroutineScope(Dispatchers.Main).launch {
            delay(duration.toLong())
            Log.d(TAG, "时间到了结束弹框$duration")
            if (easyToastView != null) {
                mWindowManager?.removeView(easyToastView)
            }
        }
    }

    fun cancelEasyToast() {
        if (easyToastView != null) {
            mWindowManager?.removeView(easyToastView)
        }
        mToastJob?.cancel()
    }
}